<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <style>
        .wrap {
            position: relative;
            width: 500px;
            height: 500px;
            background-color: #000;
        }

        .round {
            display: block;
            position: absolute;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: green;
        }

        .round.head {
            background-color: red;
        }

        .food {
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background-color: yellow;
        }
    </style>
</head>

<body>
    <div class="wrap"></div>

    <script src="js/utils.js"></script>
    <script>
        // init();
        window.onload = init

        function init() {
            this.initGame();
        }
        var initGame = (function () {
            var wrap = document.getElementsByClassName('wrap')[0],
                warpW = getStyle(wrap, 'width'),
                warpH = getStyle(wrap, 'height'),
                t = null;
            var Snake = function () {
                this.bodyArr = [{
                    x: 0,
                    y: 0
                }, {
                    x: 0,
                    y: 20
                }, {
                    x: 0,
                    y: 40
                }, {
                    x: 0,
                    y: 60
                }, {
                    x: 0,
                    y: 80
                }, {
                    x: 0,
                    y: 100
                },];
                this.dir = 'DOWN';
            }
            Snake.prototype = {
                init: function () {
                    this.initSnake();
                    this.createFood();
                    this.bindEvent();
                    this.run();

                },
                bindEvent: function () {
                    var _self = this;
                    // 绑定键盘事件
                    addEvent(document, 'keydown', function () {
                        _self.changeDir();
                    })
                },
                // 创建蛇
                initSnake: function () {
                    var arr = this.bodyArr,
                        len = arr.length,
                        // 文档碎片相当于一个容器
                        frag = document.createDocumentFragment(),
                        item;
                    for (let i = 0; i < len; i++) {
                        item = arr[i];
                        var round = document.createElement('i');
                        // 蛇的头部为红色
                        round.classList = i == len - 1 ? 'round head' : 'round';
                        round.style.left = item.x + 'px';
                        round.style.top = item.y + 'px';
                        frag.appendChild(round);
                    }
                    wrap.appendChild(frag);
                },
                // 移动
                move: function () {
                    var arr = this.bodyArr,
                        len = arr.length,
                        head = arr[len - 1];
                    for (let i = 0; i < len; i++) {
                        if (i === len - 1) {
                            // 头部移动
                            this.setHeadXY(arr);
                        } else {
                            // 身子移动
                            arr[i].x = arr[i + 1].x;
                            arr[i].y = arr[i + 1].y
                        }
                    }
                    this.removeSnake();
                    this.initSnake();
                    this.headInBody(arr);
                    this.eatFood(arr);
                },
                setHeadXY: function (arr) {
                    var head = arr[arr.length - 1];
                    switch (this.dir) {
                        case 'LEFT':
                            //判断是否到了最左侧
                            if (head.x <= 0) {
                                head.x = warpW - 20
                            } else {
                                head.x -= 20;
                            }
                            break;
                        case 'RIGHT':
                            if (head.x >= warpW - 20) {
                                head.x = 0;
                            } else {
                                head.x += 20;
                            }
                            break;
                        case 'UP':
                            if (head.y <= 0) {
                                head.y = warpH - 20;
                            } else {
                                head.y -= 20;
                            }
                            break;
                        case 'DOWN':
                            if (head.y >= warpH - 20) {
                                head.y = 0;
                            } else {
                                head.y += 20;
                            }
                            break;
                    }
                },
                headInBody: function (arr) {
                    var headX = arr[arr.length - 1].x,
                        headY = arr[arr.length - 1].y,
                        item;
                    for (var i = 0; i < arr.length - 2; i++) {
                        item = arr[i];
                        // 判断是否碰到自身，碰到游戏结束
                        if (headX === item.x && headY === item.y) {
                            var _self = this;
                            setTimeout(function () {
                                alert('游戏结束');
                                clearInterval(t);
                                _self.removeSnake();
                            }, 500)
                        }
                    }
                },
                run: function () {
                    var _self = this;
                    t = setInterval(function () {
                        _self.move();
                    }, 500)
                },
                removeSnake: function () {
                    var bodys = document.getElementsByClassName('round');
                    while (bodys.length > 0) {
                        bodys[0].remove();
                    }
                },
                changeDir: function (e) {
                    var e = e || window.event,
                        code = e.keyCode;
                    this.setDir(code);
                },
                setDir: function (code) {
                    console.log(code);
                    // 根据keycode改变方向
                    switch (code) {
                        case 37:
                            if (this.dir !== 'RIGHT' && this.dir !== 'LEFT') {
                                this.dir = 'LEFT'
                            }
                            break;
                        case 39:
                            if (this.dir !== 'RIGHT' && this.dir !== 'LEFT') {
                                this.dir = 'RIGHT'
                            }
                            break;
                        case 38:
                            if (this.dir !== 'UP' && this.dir !== 'DOWN') {
                                this.dir = 'UP'
                            }
                            break;
                        case 40:
                            if (this.dir !== 'UP' && this.dir !== 'DOWN') {
                                this.dir = 'DOWN'
                            }
                            break;
                    }
                },
                setRandomPos: function (wOrH) {
                    // console.log(Math.floor(Math.random() * (wOrH / 20)));
                    return Math.floor(Math.random() * (wOrH / 20))
                },
                createFood: function () {
                    // 创建食物
                    var food = document.createElement('i');
                    food.className = 'food';
                    food.style.left = this.setRandomPos(warpW) * 20 + 'px';
                    food.style.top = this.setRandomPos(warpH) * 20 + 'px';
                    console.log(food.style.left);
                    wrap.appendChild(food);
                },
                eatFood: function (arr) {
                    var food = document.getElementsByClassName('food')[0],
                        foodX = getStyle(food, 'left'),
                        foodY = getStyle(food, 'top'),
                        headX = arr[arr.length - 1].x,
                        headY = arr[arr.length - 1].y,
                        x, y;
                    if (headX === foodX && headY === foodY) {
                        this.removeFood();
                        this.createFood();
                        // 先判断方向，在判断最后一个坐标
                        if (arr[0].x === arr[1].x) {
                            x = arr[0].x;
                            if (arr[0].y > arr[1].y) {
                                y = arr[0].y + 20;
                            } else if (arr[0].y < arr[1].y) {
                                y = arr[0].y - 20;
                            }
                        } else if (arr[0].y === arr[1].y) {
                            y = arr[0].y;
                            if (arr[0].x > arr[0].x) {
                                x = arr[0].x + 20;
                            } else if (arr[0].x < arr[1].x) {
                                x = arr[0].x - 20;
                            }
                        }
                        arr.unshift({
                            x,
                            y
                        })
                    }
                },
                removeFood: function () {
                    var food = document.getElementsByClassName('food')[0];
                    food.remove();
                }
            }
            return new Snake().init();
        })
    </script>
</body>

</html>